package com.alxy.day1.service.impl;

import com.alxy.day1.entity.Account;
import com.alxy.day1.repository.AccountRepository;
import com.alxy.day1.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

/**
 * @author 爱莉希雅
 * @version java 17
 */
@SuppressWarnings({"all"})
@Service
public class AccountServiceImpl implements AccountService {
    @Autowired
    AccountRepository accountRepository;
    @Transactional(isolation = Isolation.REPEATABLE_READ)
   public boolean accountTransfer() {
       try {
           String programName = new String("程序1");
           //根据ID查询账户余额
           Account account1 = accountRepository.findById(1L).get();
           if (account1 == null) {
               throw new RuntimeException("账户不存在");
           }
           System.out.println(programName + "-第一次读取" + account1.getAccountName() + "的账户余额：" + account1.getBalance());
           Account account2 = accountRepository.findById(2L).get();
           if (account2 == null) {
               throw new RuntimeException("账户不存在");
           }
           System.out.println(programName + "-第一次读取" + account2.getAccountName() + "的账户余额：" + account2.getBalance());


           //用户1转账用户2 100元
           account1.setBalance(account1.getBalance().subtract(BigDecimal.valueOf(100)));
           accountRepository.saveAndFlush(account1);
           account2.setBalance(account2.getBalance().add(BigDecimal.valueOf(100)));
           accountRepository.saveAndFlush(account2);

           //睡眠创造其他事务修改余额
           Thread.sleep(30000);
           //再次读取
           Account account3 = accountRepository.findById(1L).get();
           System.out.println(programName + "-第二次读取" + account3.getAccountName() + "的账户余额：" + account3.getBalance());
           Account account4 = accountRepository.findById(2L).get();
           System.out.println(programName + "-第二次读取" + account4.getAccountName() + "的账户余额：" + account4.getBalance());
       } catch (Exception e) {
           e.printStackTrace();
           return  false;
       }
       return true;
   }
}
